<template>
  <md-main>
    <el-collapse-transition>
      <div class="md-body mb20" v-show="showSearch">
        <el-form :model="search" ref="search" size="small" :inline="true">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="search.roleName" class="w150" placeholder="请输入角色名称" clearable />
          </el-form-item>
          <el-form-item label="权限字符" prop="roleKey">
            <el-input v-model="search.roleKey" class="w150" placeholder="请输入权限字符" clearable />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <md-dict-select :options="dictData['sys_normal_disable']" v-model="search.status" placeholder="请选择状态" class="w150"></md-dict-select>
          </el-form-item>
          <el-form-item>
            <md-button type="primary" icon="el-icon-search" @click="handleQuery()">搜索</md-button>
            <md-button icon="el-icon-refresh" @click="handleQueryReset()">重置</md-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>

    <div class="md-body md-table">
      <md-toolbar>
        <md-button type="primary" size="small" plain :prems="['system:role:add']" @click="handleAdd()">新增</md-button>
        <md-button type="success" size="small" plain :prems="['system:role:remove']" :disabled="tableSelectIds.length===0" @click="handleDelete()">批量删除</md-button>

        <template slot="right">
          <md-button size="mini" icon="el-icon-search" circle @click="showSearch=!showSearch"></md-button>
          <md-button type="primary" size="mini" icon="el-icon-refresh" circle @click="getTableDataList()"></md-button>
        </template>
      </md-toolbar>

      <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleTableSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="角色编号" prop="roleId" width="120" />
        <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" />
        <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" />
        <el-table-column label="排序" prop="roleSort" />
        <el-table-column label="状态" align="center">
          <template slot-scope="{ row }">
            <el-switch v-model="row.status" active-value="0" inactive-value="1" @change="handleStatusChange(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="170">
          <template slot-scope="{ row }">
            <span>{{ row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200px" fixed="right">
          <template slot-scope="{ row }">
            <template v-if="row.roleId !== 1">
              <md-button size="mini" type="text" icon="el-icon-edit" :prems="['system:role:edit']" @click="handleUpdate(row)">修改</md-button>
              <md-button size="mini" type="text" icon="el-icon-delete" :prems="['system:role:remove']" @click="handleDelete(row)">删除</md-button>
            </template>
            <template v-else>
              <el-tag type="primary" size="mini">超级管理员</el-tag>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <md-pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="search.pageIndex" :limit.sync="search.pageSize" @pagination="getTableDataList" />
    </div>

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="request" :rules="rules" size="small" label-width="80px" label-position="right">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="request.roleName" placeholder="请输入角色名称" maxlength="30" />
        </el-form-item>

        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="request.roleKey" placeholder="请输入权限字符" maxlength="30" />
        </el-form-item>

        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="request.roleSort" label="请输入角色顺序"></el-input-number>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <md-dict-radio-group :options="dictData['sys_normal_disable']" v-model="request.status"></md-dict-radio-group>
        </el-form-item>

        <el-form-item label="菜单权限" prop="menuIds">
          <el-checkbox v-model="dialog.menuExpand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
          <el-checkbox v-model="dialog.menuNodeAll" @change="handleCheckedTreeNodeAll">全选/全不选</el-checkbox>
          <div style="border: 1px solid #ececec; width: 100%; padding: 10px; height: 180px; overflow-x: hidden; overflow-y: auto;">
            <el-tree :data="dialog.menuData" show-checkbox ref="mdMenuTree" node-key="menuId" empty-text="加载中，请稍候" :props="dialog.defaultProps"></el-tree>
          </div>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="request.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleSubmit">确 定</el-button>
        <el-button size="small" @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
  </md-main>
</template>

<script>
import { insertRole, updateRole, delRole, listPageRole, getRole } from '@/api/system/role.service.js'
import { treeListMenu, listMenu } from '@/api/system/menu.service.js'
import { mdGetDictData } from '@/ddd/dict.service.js'
export default {
  name: 'MdSystemRoleComponent',
  data () {
    return {
      // 显示隐藏查询条件
      showSearch: true,
      // 查询参数
      search: searchParams,
      // 列表加载
      tableLoading: false,
      // 列表数据
      tableData: [],
      // 列表数据，总条数
      tableTotal: 0,
      // 已选择的列表数据
      tableSelectIds: [],
      // 添加/编辑请求参数
      request: requestParams,
      rules: rules,
      // 添加/编辑弹窗
      dialog: {
        title: '添加角色',
        open: false,
        menuExpand: false,
        menuNodeAll: false,
        menuData: [],
        defaultProps: {
          children: 'children',
          label: 'menuName'
        }
      },
      dictData: {}
    }
  },
  mounted () {
    mdGetDictData(['sys_normal_disable']).then(res => {
      this.dictData = res
    })

    this.getTableDataList()
  },
  methods: {
    /** 获取角色数据 */
    async getTableDataList () {
      this.tableLoading = true
      this.tableData = []

      try {
        const res = await listPageRole(this.search)

        this.tableData = res.data.items
        this.tableTotal = res.data.totalItems
      } catch (error) {
        console.log(error)
      }

      this.tableLoading = false
    },
    /** 表格复选框事件 */
    handleTableSelectionChange (event) {
      this.tableSelectIds = event.map(m => { return m.roleId })
    },
    /** 获取菜单树 */
    async getMenuData () {
      try {
        const res = await treeListMenu({
          status: '0',
          orderBy: 'order_num',
          isDesc: false
        })

        this.dialog.menuData = res.data
      } catch (error) {
        console.log(error)
      }
    },
    /** 菜单树 - 展开/折叠 */
    async handleCheckedTreeExpand (event) {
      try {
        const res = await listMenu({
          status: '0',
          orderBy: 'order_num',
          isDesc: false
        })

        if (res.data && res.data.length > 0) {
          res.data.forEach(item => {
            this.$refs.mdMenuTree.store.nodesMap[item.menuId].expanded = event
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    /** 菜单树 - 全选/全不选 */
    handleCheckedTreeNodeAll (event) {
      this.$refs.mdMenuTree.setCheckedNodes(event ? this.dialog.menuData : [])
    },
    /** 所有菜单节点数据 */
    getMenuAllCheckedKeys () {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.mdMenuTree.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.mdMenuTree.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 搜索 */
    handleQuery () {
      this.search.pageIndex = 1

      this.getTableDataList()
    },
    /** 重置搜索 */
    handleQueryReset () {
      this.search = { ...searchParams }

      this.getTableDataList()
    },
    /** 改变用户状态事件 */
    async handleStatusChange (row) {
      try {
        const text = row.status === '0' ? '启用' : '停用'

        await this.$confirm(`确认要 ${text} ${row.roleName} 角色吗？`)

        await updateRole({ roleId: row.roleId, status: row.status })

      } catch (error) {
        console.log(error)
        row.status = row.status === '0' ? '1' : '0'
      }
    },
    // 重置表单数据
    handleReset () {
      this.request = { ...requestParams }
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    /** 删除角色 */
    async handleDelete (row) {
      try {
        const ids = row?.roleId || this.tableSelectIds

        await this.$confirm(`是否确认删除编号为${ids}的数据项？`)

        await delRole(ids)

        this.$message.success('删除成功')

        this.handleQuery()
      } catch (error) {
        console.log(error)
      }
    },
    /** 添加角色 */
    async handleAdd () {
      try {
        this.handleReset()
        this.getMenuData()

        this.dialog.title = '添加角色'

        this.dialog.open = true

        this.request = { ...requestParams }
      } catch (error) {
        console.log(error)
      }
    },
    /** 修改角色 */
    async handleUpdate (row) {
      try {
        this.handleReset()
        this.getMenuData()

        const res = await getRole(row.roleId)

        const data = res.data.role
        data.menuIds = res.data.menuIds || []

        this.request = data

        this.dialog.title = '修改角色'

        this.dialog.open = true

        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.mdMenuTree.setCheckedKeys([])
            if (this.request.menuIds.length > 0) {
              for (let index = 0; index < this.request.menuIds.length; index++) {
                const menuId = this.request.menuIds[index]
                this.$refs.mdMenuTree.setChecked(menuId, true, false)
              }
            }
          }, 200)
        })
      } catch (error) {
        console.log(error)
      }
    },
    /** 提交 */
    handleSubmit () {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }

        try {
          const params = Object.assign({}, { ...this.request })

          params.menuIds = this.getMenuAllCheckedKeys()

          await (params.roleId === undefined ? insertRole : updateRole)(params)

          this.$message.success(params.roleId === undefined ? '添加成功' : '修改成功')

          this.dialog.open = false;

          this.handleQuery()
        } catch (error) {
          console.log(error)
        }
      })
    },
    /** 取消 */
    handleCancel () {
      this.dialog.open = false

      this.handleReset()
    }
  }
}
const searchParams = {
  roleName: undefined,
  roleKey: undefined,
  dataScope: undefined,
  menuCheckStrictly: undefined,
  deptCheckStrictly: undefined,
  status: undefined,
  createBy: undefined,
  updateBy: undefined,
  beginDate: undefined,
  endDate: undefined,
  orderBy: 'role_sort',
  isDesc: false,
  pageIndex: 1,
  pageSize: 10

}
const requestParams = {
  roleId: undefined,
  roleName: undefined,
  roleKey: undefined,
  roleSort: 100,
  dataScope: 1,
  menuCheckStrictly: 1,
  deptCheckStrictly: 1,
  status: '0',
  remark: undefined,
  menuIds: [],
  deptIds: []
}

const rules = {
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  roleKey: [{ required: true, message: '请输入权限字符', trigger: 'blur' }]
}
</script>